﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Threading;
using System.Xml.XPath;
using EnvDTE;
using EnvDTE80;
using Microsoft.Expression.Media.Effects;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using WindowsPhoneToolbox.Util;
using AppRes = WindowsPhoneToolbox.Resources;
using AppConst = WindowsPhoneToolbox.Util.Constants;
using System.Xml;
using System.Text;

namespace WindowsPhoneToolbox.Controls
{
    /// <summary>
    /// Interaction logic for EditManifestControl.xaml
    /// </summary>
    public partial class EditManifestControl : INotifyPropertyChanged
    {
        private readonly DTE2 _dte;
        private Dictionary<string, string> _sourceProjects;
        private bool _refreshAfterEndEdit;
        private readonly SolutionEvents _solutionEvents;
        private List<string> _pathPrjectsName;
        private bool _executechangeIndex;
        private Project _seletedProject;
        private List<string> _imagesSeletedProject;
        private List<string> _fileXamlseletedProject;
        private string _errsFromManifest;
        private bool _isVisible;
        private string _xmlManifestOrig;

        private class AdorneLst
        {
            public Control ControlErr { get; set; }
            public Brush DefaultBrush { get; set; }
        }

        private readonly List<AdorneLst> _adorneErroControls = new List<AdorneLst>();

        public EditManifestControl()
        {
            InitializeComponent();

            _executechangeIndex = true;
            _sourceProjects = new Dictionary<string, string>();
            _pathPrjectsName = new List<string>();
            _dte = Package.GetGlobalService(typeof(SDTE)) as DTE2;
            if (_dte != null)
            {
                _solutionEvents = _dte.Events.SolutionEvents;

                _solutionEvents.AfterClosing += (SolutionEventsAfterClosing);
                _solutionEvents.Opened += (SolutionEventsOpened);
                _solutionEvents.ProjectRemoved += SolutionEventsProjectRemoved;
                _solutionEvents.ProjectAdded += SolutionEventsProjectAdded;
                _solutionEvents.ProjectRenamed += SolutionEventsProjectRenamed;
            }
            ClearEdit();
            BntSave.IsEnabled = false;
        }

        public bool HasSolution
        {
            get { return _dte.Solution.Projects.Count > 0; }
        }

        public Effect MenuEfect
        {
            get
            {
                if (HasSolution)
                {
                    return null;
                }
                var effect = new BloomEffect { BloomSaturation = 0.01, BaseIntensity = 0.16, BloomIntensity = 0.45 };
                return effect;
            }
        }

        private void SolutionEventsOpened()
        {
            NotifyPropertyChanged("HasSolution");
            NotifyPropertyChanged("MenuEfect");

            _isVisible = (Visibility == Visibility.Visible);
            if (_isVisible)
            {
                Refreshprojects();
            }
        }

        private void SolutionEventsAfterClosing()
        {
            NotifyPropertyChanged("HasSolution");
            NotifyPropertyChanged("MenuEfect");

            _solutionEvents.ProjectRemoved -= (SolutionEventsProjectRemoved);
            _solutionEvents.ProjectAdded -= (SolutionEventsProjectAdded);
            _solutionEvents.ProjectRenamed -= (SolutionEventsProjectRenamed);

            ClearEdit();
            _sourceProjects.Clear();
            _pathPrjectsName.Clear();
        }

        private void SolutionEventsProjectRenamed(Project project, string oldName)
        {
            if (!_isVisible) return;

            var index = CboProjects.SelectedIndex;
            if (index >= 0 && _pathPrjectsName[index] == oldName)
            {
                _executechangeIndex = false;
                CboProjects.Items[index] = project.Name;
                CboProjects.SelectedIndex = index;
                _executechangeIndex = true;
                _pathPrjectsName[index] = project.FullName;
            }
            else
            {
                for (var i = 0; i < CboProjects.Items.Count; i++)
                {
                    if (_pathPrjectsName[i] == oldName)
                    {
                        _executechangeIndex = false;
                        CboProjects.Items[i] = project.Name;
                        _executechangeIndex = true;
                        _pathPrjectsName[i] = project.FullName;
                        break;
                    }
                }
            }
            var keys = _sourceProjects.Keys;
            var remkey = string.Empty;
            var irem = 0;
            foreach (var key in keys)
            {
                if (irem == index)
                {
                    remkey = key;
                    break;
                }
                irem++;
            }
            var path = _sourceProjects[remkey];
            _sourceProjects.Remove(remkey);
            _sourceProjects.Add(project.Name, path);
        }

        private void SolutionEventsProjectAdded(Project project)
        {
            NotifyPropertyChanged("HasSolution");
            NotifyPropertyChanged("MenuEfect");

            if (!_isVisible) return;

            try
            {
                var pathDefault = Common.GetPathFileManifest(project);
                if (!string.IsNullOrEmpty(pathDefault))
                {
                    _sourceProjects.Add(project.Name, pathDefault);
                    _pathPrjectsName.Add(project.FullName);
                    _executechangeIndex = false;
                    CboProjects.Items.Add(project.Name);
                    _executechangeIndex = true;
                }
            }
            catch (Exception ex)
            {
                _errsFromManifest = ex.ToString();
                BntErro.Visibility = Visibility.Visible;
                MessageBox.Show(AppRes.ErrFindMnf, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                CboProjects.SelectedIndex = -1;
                BntSave.IsEnabled = false;
            }
        }

        private void SolutionEventsProjectRemoved(Project project)
        {
            NotifyPropertyChanged("HasSolution");
            NotifyPropertyChanged("MenuEfect");

            if (!_isVisible) return;

            var index = CboProjects.SelectedIndex;
            if (index >= 0 && (string)CboProjects.Items[index] == project.Name)
            {
                ClearEdit();
                return;
            }
            var keys = _sourceProjects.Keys;
            var idel = 0;
            foreach (var key in keys)
            {
                if (key == project.Name)
                {
                    _sourceProjects.Remove(key);
                    _pathPrjectsName.RemoveAt(idel);
                    _executechangeIndex = false;
                    CboProjects.Items.RemoveAt(idel);
                    _executechangeIndex = true;
                    break;
                }
                idel++;
            }
        }

        private void Refreshprojects()
        {
            if (!_isVisible) return;

            WaitReading.Visibility = Visibility.Visible;
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(BackgroundRefresh));
        }

        private void BackgroundRefresh()
        {
            IsEnabled = false;
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            ClearEdit();
            BntSave.IsEnabled = false;
            LoadProjects();
            WaitReading.Visibility = Visibility.Collapsed;
            Cursor = oldcur;
            IsEnabled = true;
        }

        private void LoadProjects()
        {
            _sourceProjects = new Dictionary<string, string>();
            _pathPrjectsName = new List<string>();
            CboProjects.Items.Clear();
            CboProjects.SelectedIndex = -1;
            BntErro.Visibility = Visibility.Collapsed;
            _errsFromManifest = string.Empty;
            try
            {
                var prjs = _dte.Solution.Projects;
                foreach (var prj in from Project proj in prjs select proj)
                {
                    if (prj.ProjectItems != null)
                    {
                        var items = prj.ProjectItems.GetEnumerator();
                        while (items.MoveNext())
                        {
                            var result = Common.GetPathFileManifest((ProjectItem)items.Current);
                            if (!String.IsNullOrEmpty(result))
                            {
                                _sourceProjects.Add(prj.Name, result);
                                _pathPrjectsName.Add(prj.FullName);
                                break;
                            }
                        }
                    }
                }
                if (_sourceProjects.Count > 0)
                {
                    foreach (var key in _sourceProjects.Keys)
                    {
                        CboProjects.Items.Add(key);
                    }
                }
            }
            catch (Exception ex)
            {
                _errsFromManifest = ex.ToString();
                BntErro.Visibility = Visibility.Visible;
                MessageBox.Show(AppRes.ErrReadingPrjSol, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                BntSave.IsEnabled = false;
            }
        }

        private void EnabledDisabledEdit(bool enabled)
        {
            TxtTitle.IsEnabled = enabled;
            TxtAuthor.IsEnabled = enabled;
            TxtDesc.IsEnabled = enabled;
            TxtPublisher.IsEnabled = enabled;
            StackVersion.IsEnabled = enabled;
            StackMoreInfo.IsEnabled = enabled;
            StackCapabilities.IsEnabled = enabled;
            TxtTokenID.IsEnabled = enabled;
            ChkUpdTile.IsEnabled = enabled;
            ChkUpdToken.IsEnabled = enabled;
            ChkUpdTile.IsEnabled = enabled;
            CboIconAppp.IsEnabled = enabled;
            CboIconBg.IsEnabled = enabled;
            CboNavPage.IsEnabled = enabled;
            TxtTileCount.IsEnabled = enabled;
            TxtTileTitle.IsEnabled = enabled;
            if (ChkUpdTile.IsChecked != null && (bool)ChkUpdTile.IsChecked)
            {
                TxtTileTitle.IsEnabled = false;
            }
            if (ChkUpdToken.IsChecked != null && (bool)ChkUpdToken.IsChecked)
            {
                TxtTokenID.IsEnabled = false;
            }
        }

        private void ClearEdit()
        {
            _executechangeIndex = false;
            EnabledDisabledEdit(false);
            ClearAdorneErroUiElement();
            _xmlManifestOrig = string.Empty;
            CboProjects.SelectedIndex = -1;
            BntErro.Visibility = Visibility.Collapsed;
            _errsFromManifest = string.Empty;
            _seletedProject = null;
            _imagesSeletedProject = new List<string>();
            _fileXamlseletedProject = new List<string>();

            TxtTitle.Text = string.Empty;
            TxtAuthor.Text = string.Empty;
            TxtDesc.Text = string.Empty;
            TxtPublisher.Text = string.Empty;
            VerMaior.Text = string.Empty;
            VerMaior.Text = string.Empty;
            VerMenor.Text = string.Empty;
            VerRev.Text = string.Empty;
            VerBuild.Text = string.Empty;
            opt16pixel.IsChecked = true;
            foreach (var checkBox in StackMoreInfo.Children.OfType<CheckBox>())
            {
                (checkBox).IsChecked = false;
            }
            StackCapabilities.IsEnabled = false;
            foreach (var checkBox in StackCapabilities.Children.OfType<CheckBox>())
            {
                (checkBox).IsChecked = false;
            }
            TxtTokenID.Text = string.Empty;
            ChkUpdTile.IsChecked = true;
            ChkUpdToken.IsChecked = false;
            CboIconAppp.SelectedIndex = -1;
            CboIconBg.SelectedIndex = -1;
            CboNavPage.SelectedIndex = -1;
            CboIconAppp.ItemsSource = null;
            CboIconBg.ItemsSource = null;
            CboNavPage.ItemsSource = null;
            TxtTileCount.Text = string.Empty;
            TxtTileTitle.Text = string.Empty;
            ClearAdorneErroUiElement();
            _executechangeIndex = true;
        }

        private void BntRefreshClick(object sender, RoutedEventArgs e)
        {
            Refreshprojects();
        }

        private void CboProjectsSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isVisible || !_executechangeIndex) return;

            _errsFromManifest = string.Empty;
            BntErro.Visibility = Visibility.Collapsed;

            var newindex = ((ComboBox)sender).SelectedIndex;
            if (newindex < 0)
            {
                ClearEdit();
            }
            else
            {
                _seletedProject = Common.FindProjectByName(_dte, (string)CboProjects.SelectedItem);
                var docs = _dte.Documents;
                var enumdocs = docs.GetEnumerator();
                Document docEdit = null;
                while (enumdocs.MoveNext())
                {
                    var doc = (Document)enumdocs.Current;
                    if (doc.FullName == _sourceProjects[(string)CboProjects.SelectedItem])
                    {
                        docEdit = doc;
                        break;
                    }
                }
                if (docEdit == null)
                {
                    var subitems = _seletedProject.ProjectItems.GetEnumerator();
                    while (subitems.MoveNext())
                    {
                        var tmp = Common.GetManifestWp((ProjectItem)subitems.Current);
                        if (tmp != null)
                        {
                            tmp.Open();
                            docEdit = tmp.Document;
                            break;
                        }
                    }
                }
                if (docEdit == null)
                {
                    throw new Exception(AppRes.ManifNotFound);
                }
                if (!docEdit.Saved)
                {
                    var result = MessageBox.Show(AppRes.QSaveManifest, AppRes.TitleWindows,
                                                 MessageBoxButton.YesNo, MessageBoxImage.Question);
                    if (result == MessageBoxResult.No)
                    {
                        CboProjects.SelectedIndex = -1;
                        return;
                    }
                    docEdit.Save();
                }

                WaitReading.Visibility = Visibility.Visible;
                var args = new List<object> { docEdit };
                Dispatcher.BeginInvoke(DispatcherPriority.Background, new ChangeProjectCommandHandle(BackgroundChangeProject),args.ToArray());
            }
        }

        private delegate void ChangeProjectCommandHandle(object[] args);

        private void BackgroundChangeProject(object[] args)
        {
            var docEdit = (Document)args[0];
            IsEnabled = false;
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            ClearAdorneErroUiElement();
            try
            {
                _imagesSeletedProject = Common.GetListFilesFromProject(_seletedProject,
                                                                       new[] { ".PNG", ".JPG", ".JPEG", ".BMP" });

                _fileXamlseletedProject = Common.GetListFilesFromProject(_seletedProject,
                                                                       new[] { ".XAML" });

                CboIconAppp.ItemsSource = _imagesSeletedProject;
                CboIconBg.ItemsSource = _imagesSeletedProject;
                CboNavPage.ItemsSource = _fileXamlseletedProject;

                try
                {
                    _errsFromManifest = ShowInfoManifest(docEdit);
                    WaitReading.Visibility = Visibility.Collapsed;
                    if (_errsFromManifest.Length != 0)
                    {
                        BntErro.Visibility = Visibility.Visible;
                        Cursor = oldcur;
                        MessageBox.Show(AppRes.ManifInvalidValue, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                    EnabledDisabledEdit(true);
                    BntSave.IsEnabled = true;

                }
                catch (Exception ex)
                {
                    ClearEdit();
                    WaitReading.Visibility = Visibility.Collapsed;
                    _errsFromManifest = ex.ToString();
                    BntErro.Visibility = Visibility.Visible;
                    BntSave.IsEnabled = false;
                    Cursor = oldcur;
                    MessageBox.Show(AppRes.ErrReadindManifFile, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                ClearEdit();
                WaitReading.Visibility = Visibility.Collapsed;
                _errsFromManifest = ex.ToString();
                BntErro.Visibility = Visibility.Visible;
                BntSave.IsEnabled = false;
                Cursor = oldcur;
                MessageBox.Show(AppRes.ErrReadindManifPrj, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Cursor = oldcur;
            IsEnabled = true;
        }

        private string ShowInfoManifest(Document docEdit)
        {
            var errors = string.Empty;
            _xmlManifestOrig = string.Empty;
            var textselect = (TextSelection)docEdit.Selection;
            textselect.SelectAll();
            _xmlManifestOrig = textselect.Text;
            docEdit.Close();

            var memStr = new MemoryStream(Encoding.UTF8.GetBytes(_xmlManifestOrig));
            var xpathDoc = new XPathDocument(memStr);
            memStr.Close();

            var navigator = xpathDoc.CreateNavigator().SelectSingleNode("//App");

            if (navigator == null)
            {
                throw new Exception(AppRes.ErrNodeAppNotFound);
            }


            // ReSharper disable PossibleNullReferenceException
            TxtTitle.Text = Common.XmlUnescape(navigator.GetAttribute("Title", string.Empty).Trim());
            if (TxtTitle.Text.Length == 0)
            {
                AdorneErroUiElement(TxtTitle);
                errors += string.Format(AppRes.ErrNodeAppAttribEmpty,AppRes.XTitle);
            }
            // ReSharper restore PossibleNullReferenceException
            TxtAuthor.Text = Common.XmlUnescape(navigator.GetAttribute("Author", string.Empty).Trim());
            if (TxtAuthor.Text.Length == 0)
            {
                AdorneErroUiElement(TxtAuthor);
                errors += string.Format(AppRes.ErrNodeAppAttribEmpty, AppRes.XAuthor);
            }
            TxtDesc.Text = Common.XmlUnescape(navigator.GetAttribute("Description", string.Empty).Trim());
            if (TxtDesc.Text.Length == 0)
            {
                AdorneErroUiElement(TxtDesc);
                errors += string.Format(AppRes.ErrNodeAppAttribEmpty, AppRes.XDescription);
            }
            TxtPublisher.Text = Common.XmlUnescape(navigator.GetAttribute("Publisher", string.Empty).Trim());
            if (TxtPublisher.Text.Length == 0)
            {
                AdorneErroUiElement(TxtPublisher);
                errors += string.Format(AppRes.ErrNodeAppAttribEmpty, AppRes.XPublisher);
            }

            var version = navigator.GetAttribute("Version", string.Empty).Split('.');
            if (version.Length < 2 || version.Length > 4)
            {
                if (TxtDesc.Text.Length == 0)
                {
                    errors += AppRes.ErrNodeAppVersion;
                }
                AdorneErroUiElement(VerMaior);
                AdorneErroUiElement(VerMenor);
                AdorneErroUiElement(VerRev);
                AdorneErroUiElement(VerBuild);
            }
            else
            {
                int tmptryint;
                var vererr = false;
                if (!int.TryParse(version[0], out tmptryint))
                {
                    vererr  = true;
                    AdorneErroUiElement(VerMaior);
                }
                if (!int.TryParse(version[1], out tmptryint))
                {
                    vererr = true;
                    AdorneErroUiElement(VerMenor);
                }
                if (version.Length >= 3)
                {
                    if (!int.TryParse(version[2], out tmptryint))
                    {
                        vererr = true;
                        AdorneErroUiElement(VerRev);
                    }
                }
                if (version.Length == 4)
                {
                    if (!int.TryParse(version[3], out tmptryint))
                    {
                        vererr = true;
                        AdorneErroUiElement(VerBuild);
                    }
                }
                if (vererr)
                {
                    errors += AppRes.ErrNodeAppVersion;
                }
            }

            VerMaior.Text = version[0];
            VerMenor.Text = version[1];
            if (version.Length >= 3)
            {
                VerRev.Text = version[2];
            }
            if (version.Length == 4)
            {
                VerBuild.Text = version[3];
            }
            try
            {
                ChkHasSettings.IsChecked = Common.XmlBoolConvert(navigator.GetAttribute("HasSettings", string.Empty), false,true);
            }
            catch (Exception)
            {
                errors += AppRes.ErrNodeAppHasSett;
                AdorneErroUiElement(ChkHasSettings);
                AdorneErroUiElement(ExpMore);
            }
            try
            {
                ChkIsBeta.IsChecked = Common.XmlBoolConvert(navigator.GetAttribute("IsBeta", string.Empty), false,true);
            }
            catch (Exception)
            {
                errors += AppRes.ErrNodeAppIsBeta;
                AdorneErroUiElement(ChkIsBeta);
                AdorneErroUiElement(ExpMore);
            }
            try
            {
                ChkSingleInst.IsChecked = Common.XmlBoolConvert(navigator.GetAttribute("SingleInstanceHost", string.Empty), false,true);
            }
            catch (Exception)
            {
                errors += AppRes.ErrNodeAppSingInst;
                AdorneErroUiElement(ChkSingleInst);
                AdorneErroUiElement(ExpMore);
            }
            var ht = navigator.GetAttribute("HubType", string.Empty);
            if (ht != "0" && ht != "1" && !string.IsNullOrEmpty(ht))
            {
                errors += AppRes.ErrNodeApphupType;
                AdorneErroUiElement(ChkHubType1);
                AdorneErroUiElement(ExpMore);
            }
            else
            {
                ChkHubType1.IsChecked = (ht == "1");
            }

            var pixel = Common.XmlBitPixelConvert(navigator.GetAttribute("BitsPerPixel", string.Empty));

            if (pixel != "16" && pixel != "32" && !string.IsNullOrEmpty(pixel))
            {
                errors += AppRes.ErrNodeAppPixel;
                AdorneErroUiElement(opt16pixel);
                AdorneErroUiElement(opt32pixel);
                AdorneErroUiElement(ExpMore);
                opt16pixel.IsChecked = false;
                opt32pixel.IsChecked = false;
            }
            else
            {
                opt16pixel.IsChecked = (pixel == "16");
                opt32pixel.IsChecked = (pixel == "32");
            }

            var selectSingleNode = navigator.SelectSingleNode("//App//IconPath");
            if (selectSingleNode == null)
            {
                throw new Exception(AppRes.ErrNodeIconPath);
            }
            var iconApp = Common.XmlUnescape(selectSingleNode.ToString());
            if (!_imagesSeletedProject.Any(i => i == iconApp))
            {
                errors += string.Format(AppRes.ErrNodeIconPathFileNotFound,iconApp);
                CboIconAppp.SelectedIndex = -1;
                AdorneErroUiElement(CboIconAppp);
            }
            else
            {
                CboIconAppp.Text = iconApp;
            }
            selectSingleNode = navigator.SelectSingleNode("//App//Capabilities");
            if (selectSingleNode == null)
            {
                throw new Exception(AppRes.ErrNodeCap);
            }
            if (selectSingleNode.HasChildren)
            {
                var capabilitiesNodes = selectSingleNode.SelectChildren("", string.Empty);
                while (capabilitiesNodes.MoveNext())
                {
                    var cap = capabilitiesNodes.Current.GetAttribute("Name", string.Empty);
                    switch (cap)
                    {
                        case AppConst.IdCapAppointments:
                            ChkAppointments.IsChecked = true;
                            break;
                        case AppConst.IdCapContacts:
                            ChkContacts.IsChecked = true;
                            break;
                        case AppConst.IdCapGamerservices:
                            ChkGamerSrv.IsChecked = true;
                            break;
                        case AppConst.IdCapIdentityDevice:
                            ChkIdentDevive.IsChecked = true;
                            break;
                        case AppConst.IdCapIdentityUser:
                            ChkIdentUser.IsChecked = true;
                            break;
                        case AppConst.IdCapIsvCamera:
                            ChkCamera.IsChecked = true;
                            break;
                        case AppConst.IdCapLocation:
                            ChkLocation.IsChecked = true;
                            break;
                        case AppConst.IdCapMedialib:
                            ChkMediaLib.IsChecked = true;
                            break;
                        case AppConst.IdCapMicrophone:
                            ChkMicrophone.IsChecked = true;
                            break;
                        case AppConst.IdCapNetworking:
                            ChkNetworking.IsChecked = true;
                            break;
                        case AppConst.IdCapPhonedialer:
                            ChkPhoneDialer.IsChecked = true;
                            break;
                        case AppConst.IdCapPushNotification:
                            ChkPushNotif.IsChecked = true;
                            break;
                        case AppConst.IdCapSensors:
                            ChkSensor.IsChecked = true;
                            break;
                        case AppConst.IdCapWebbrowsercomponent:
                            ChkWebBrowser.IsChecked = true;
                            break;
                        default:
                            errors += string.Format(AppRes.ErrNodeCapValue,cap );
                            AdorneErroUiElement(ExpCap);
                            break;
                    }
                }
            }
            selectSingleNode = navigator.SelectSingleNode("//App//Tasks//DefaultTask");
            if (selectSingleNode == null)
            {
                throw new Exception(AppRes.ErrNodeDefTask);
            }
            var navpg = Common.XmlUnescape(selectSingleNode.GetAttribute("NavigationPage", string.Empty));
            if (!_fileXamlseletedProject.Any(p => p == navpg))
            {
                errors += string.Format(AppRes.ErrNodeNavpgNotFound,navpg );
                CboNavPage.SelectedIndex = -1;
                AdorneErroUiElement(CboNavPage);
            }
            else
            {
                CboNavPage.Text = navpg;
            }
            selectSingleNode = navigator.SelectSingleNode("//App//Tokens//PrimaryToken");
            if (selectSingleNode == null)
            {
                throw new Exception(AppRes.ErrNodePTk);
            }
            TxtTokenID.Text = Common.XmlUnescape(selectSingleNode.GetAttribute("TokenID", string.Empty));
            if (TxtTokenID.Text.Length == 0)
            {
                errors += AppRes.ErrNodeTKId;
                AdorneErroUiElement(TxtTokenID);
            }
            selectSingleNode = navigator.SelectSingleNode("//App//Tokens//PrimaryToken//TemplateType5//BackgroundImageURI");
            if (selectSingleNode == null)
            {
                throw new Exception(AppRes.ErrNodeBgImg);
            }
            var imgbg = Common.XmlUnescape(selectSingleNode.Value);
            if (!_imagesSeletedProject.Any(p => p == imgbg))
            {
                errors += string.Format(AppRes.ErrNodeBgImgFile,imgbg);
                CboIconBg.SelectedIndex = -1;
                AdorneErroUiElement(CboIconBg);
                AdorneErroUiElement(ExpTile);
            }
            else
            {
                CboIconBg.Text = imgbg;
            }
            selectSingleNode = navigator.SelectSingleNode("//App//Tokens//PrimaryToken//TemplateType5//Count");
            if (selectSingleNode == null)
            {
                throw new Exception(AppRes.ErrNodeTileCount);
            }
            var tlc = selectSingleNode.Value;
            int tmpint;
            if (!int.TryParse(tlc,out tmpint))
            {
                errors += AppRes.ErrNodeTileCountRanger;
                AdorneErroUiElement(TxtTileCount);
                AdorneErroUiElement(ExpTile);
                TxtTileCount.Text = string.Empty;
            }
            else
            {
                if (tmpint < 0 || tmpint > 99)
                {
                    errors += AppRes.ErrNodeTileCountRanger;
                    AdorneErroUiElement(TxtTileCount);
                    AdorneErroUiElement(ExpTile);
                    TxtTileCount.Text = string.Empty;
                }
                else
                {
                    TxtTileCount.Text = tlc;
                }
            }
            selectSingleNode = navigator.SelectSingleNode("//App//Tokens//PrimaryToken//TemplateType5//Title");
            if (selectSingleNode == null)
            {
                throw new Exception(AppRes.ErrNodeTitleTile);
            }
            TxtTileTitle.Text = Common.XmlUnescape(selectSingleNode.Value);
            return errors;
        }

        private void BntSaveClick(object sender, RoutedEventArgs e)
        {
            try
            {
                #pragma warning disable 168
                var dummy = _seletedProject.Name;
                #pragma warning restore 168
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            } 
            if (_adorneErroControls.Count > 0)
            {
                MessageBox.Show(AppRes.CorrectFist, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            WaitReading.Tag = WaitReading.Text;
            WaitReading.Text = AppRes.WaitSave;
            WaitReading.Visibility = Visibility.Visible;
            BntSave.IsEnabled = false;
            IsEnabled = false;
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(BackgroundSaveManifest));


        }

        private void BackgroundSaveManifest()
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            var haserro = false;
            try
            {
                // ReSharper disable PossibleNullReferenceException
                var xmldoc = new XmlDocument();
                xmldoc.LoadXml(_xmlManifestOrig);
                var selectedNode = xmldoc.GetElementsByTagName("App")[0];
                selectedNode.Attributes["Title"].Value = Common.XmlEscape(TxtTitle.Text.Trim());
                var ver = VerMaior.Text.Trim() + "." + VerMenor.Text.Trim();
                if (VerRev.Text.Trim().Length > 0)
                {
                    ver += "." + VerRev.Text.Trim();
                    if (VerBuild.Text.Trim().Length > 0)
                    {
                        ver += "." + VerBuild.Text.Trim();
                    }
                }
                selectedNode.Attributes["Version"].Value = ver;
                selectedNode.Attributes["Author"].Value = Common.XmlEscape(TxtAuthor.Text.Trim());
                selectedNode.Attributes["Description"].Value = Common.XmlEscape(TxtDesc.Text.Trim());
                selectedNode.Attributes["Publisher"].Value = Common.XmlEscape(TxtPublisher.Text.Trim());
                if (ChkHubType1.IsChecked != null && ChkHubType1.IsChecked.Value)
                {
                    if (selectedNode.Attributes["HubType"] == null)
                    {
                        var newatt = xmldoc.CreateAttribute("HubType");
                        newatt.Value = "1";
                        selectedNode.Attributes.Append(newatt);
                    }
                    else
                    {
                        selectedNode.Attributes["HubType"].Value = "1";
                    }
                }
                else
                {
                    if (selectedNode.Attributes["HubType"] != null)
                    {
                        selectedNode.Attributes.Remove(selectedNode.Attributes["HubType"]);
                    }
                }
                if (ChkIsBeta.IsChecked != null && ChkIsBeta.IsChecked.Value)
                {
                    if (selectedNode.Attributes["IsBeta"] == null)
                    {
                        var newatt = xmldoc.CreateAttribute("IsBeta");
                        newatt.Value = bool.TrueString.ToLower();
                        selectedNode.Attributes.Append(newatt);
                    }
                    else
                    {
                        selectedNode.Attributes["IsBeta"].Value = bool.TrueString.ToLower();
                    }
                }
                else
                {
                    if (selectedNode.Attributes["IsBeta"] != null)
                    {
                        selectedNode.Attributes.Remove(selectedNode.Attributes["IsBeta"]);
                    }
                }
                if (ChkHasSettings.IsChecked != null && ChkHasSettings.IsChecked.Value)
                {
                    if (selectedNode.Attributes["HasSettings"] == null)
                    {
                        var newatt = xmldoc.CreateAttribute("HasSettings");
                        newatt.Value = bool.TrueString.ToLower();
                        selectedNode.Attributes.Append(newatt);
                    }
                    else
                    {
                        selectedNode.Attributes["HasSettings"].Value = bool.TrueString.ToLower();
                    }
                }
                else
                {
                    if (selectedNode.Attributes["HasSettings"] != null)
                    {
                        selectedNode.Attributes.Remove(selectedNode.Attributes["HasSettings"]);
                    }
                }
                if (ChkSingleInst.IsChecked != null && ChkSingleInst.IsChecked.Value)
                {
                    if (selectedNode.Attributes["SingleInstanceHost"] == null)
                    {
                        var newatt = xmldoc.CreateAttribute("SingleInstanceHost");
                        newatt.Value = bool.TrueString.ToLower();
                        selectedNode.Attributes.Append(newatt);
                    }
                    else
                    {
                        selectedNode.Attributes["SingleInstanceHost"].Value = bool.TrueString.ToLower();
                    }
                }
                else
                {
                    if (selectedNode.Attributes["SingleInstanceHost"] != null)
                    {
                        selectedNode.Attributes.Remove(selectedNode.Attributes["SingleInstanceHost"]);
                    }
                }
                if (opt32pixel.IsChecked != null && opt32pixel.IsChecked.Value)
                {
                    if (selectedNode.Attributes["BitsPerPixel"] == null)
                    {
                        var newatt = xmldoc.CreateAttribute("BitsPerPixel");
                        newatt.Value = "32";
                        selectedNode.Attributes.Append(newatt);
                    }
                    else
                    {
                        selectedNode.Attributes["BitsPerPixel"].Value = "32";
                    }
                }
                else
                {
                    if (selectedNode.Attributes["BitsPerPixel"] != null)
                    {
                        selectedNode.Attributes.Remove(selectedNode.Attributes["BitsPerPixel"]);
                    }
                }

                selectedNode = xmldoc.GetElementsByTagName("IconPath")[0];
                selectedNode.InnerText = Common.XmlEscape(CboIconAppp.Text);

                selectedNode = xmldoc.GetElementsByTagName("Capabilities")[0];
                selectedNode.RemoveAll();
                if (ChkGamerSrv.IsChecked != null && ChkGamerSrv.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapGamerservices;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkIdentDevive.IsChecked != null && ChkIdentDevive.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapIdentityDevice;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkIdentUser.IsChecked != null && ChkIdentUser.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapIdentityUser;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkLocation.IsChecked != null && ChkLocation.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapLocation;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkMediaLib.IsChecked != null && ChkMediaLib.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapMedialib;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkMicrophone.IsChecked != null && ChkMicrophone.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapMicrophone;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkNetworking.IsChecked != null && ChkNetworking.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapNetworking;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkPhoneDialer.IsChecked != null && ChkPhoneDialer.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapPhonedialer;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkPushNotif.IsChecked != null && ChkPushNotif.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapPushNotification;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkSensor.IsChecked != null && ChkSensor.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapSensors;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkWebBrowser.IsChecked != null && ChkWebBrowser.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapWebbrowsercomponent;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkCamera.IsChecked != null && ChkCamera.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapIsvCamera;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkContacts.IsChecked != null && ChkContacts.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapContacts;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }
                if (ChkAppointments.IsChecked != null && ChkAppointments.IsChecked.Value)
                {
                    var newcap = xmldoc.CreateNode(XmlNodeType.Element, "Capability", string.Empty);
                    var newatt = xmldoc.CreateAttribute("Name");
                    newatt.Value = AppConst.IdCapAppointments;
                    newcap.Attributes.Append(newatt);
                    selectedNode.AppendChild(newcap);
                }

                selectedNode = xmldoc.GetElementsByTagName("DefaultTask")[0];
                selectedNode.Attributes["NavigationPage"].Value = Common.XmlEscape(CboNavPage.Text);

                selectedNode = xmldoc.GetElementsByTagName("PrimaryToken")[0];
                selectedNode.Attributes["TokenID"].Value = Common.XmlEscape(TxtTokenID.Text.Trim());

                selectedNode = xmldoc.GetElementsByTagName("TemplateType5")[0];
                foreach (XmlNode item in selectedNode.ChildNodes)
                {
                    if (item.NodeType == XmlNodeType.Element && item.Name == "BackgroundImageURI")
                    {
                        item.InnerText = Common.XmlEscape(CboIconBg.Text);
                    }
                    else if (item.NodeType == XmlNodeType.Element && item.Name == "Count")
                    {
                        item.InnerText = TxtTileCount.Text.Trim();
                    }
                    else if (item.NodeType == XmlNodeType.Element && item.Name == "Title")
                    {
                        item.InnerText = Common.XmlEscape(TxtTileTitle.Text.Trim());
                    }
                }
                // ReSharper restore PossibleNullReferenceException


                var docs = _dte.Documents;
                var enumdocs = docs.GetEnumerator();
                Document docEdit = null;
                while (enumdocs.MoveNext())
                {
                    var doc = (Document)enumdocs.Current;
                    if (doc.FullName == _sourceProjects[(string)CboProjects.SelectedItem])
                    {
                        docEdit = doc;
                        docEdit.Activate();
                        break;
                    }
                }
                if (docEdit == null)
                {
                    var subitems = _seletedProject.ProjectItems.GetEnumerator();
                    while (subitems.MoveNext())
                    {
                        var tmp = Common.GetManifestWp((ProjectItem)subitems.Current);
                        if (tmp != null)
                        {
                            tmp.Open();
                            docEdit = tmp.Document;
                            docEdit.Activate();
                            break;
                        }
                    }
                }
                if (docEdit == null)
                {
                    haserro = true;
                    MessageBox.Show(AppRes.ManifNotFound, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    var settings = new XmlWriterSettings
                    {
                        Indent = true,
                        IndentChars = "\t",
                        OmitXmlDeclaration = true,
                        NewLineOnAttributes = false
                    };

                    var output = new StringBuilder();
                    var writer = XmlWriter.Create(output, settings);
                    xmldoc.WriteContentTo(writer);
                    writer.Flush();

                    var textselect = (TextSelection)docEdit.Selection;
                    textselect.SelectAll();
                    textselect.Insert(output.ToString());
                    textselect.GotoLine(1);
                    docEdit.Save();
                    docEdit.Activate();
                    writer.Close();
                }
            }
            catch (Exception ex)
            {
                haserro = true;
                MessageBox.Show(AppRes.ErrSavingFileManif + ex, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
            }

            IsEnabled = true;
            Cursor = oldcur;
            WaitReading.Visibility = Visibility.Collapsed;
            WaitReading.Text = WaitReading.Tag.ToString();

            if (!haserro)
            {
                if (_refreshAfterEndEdit)
                {
                    _refreshAfterEndEdit = false;
                    LoadProjects();
                }
                else
                {
                    CboProjects.SelectedIndex = -1;
                }
            }
            IsEnabled = true;
        }

        private void ChkUpdTileClick(object sender, RoutedEventArgs e)
        {
            if (ChkUpdTile.IsChecked != null && ChkUpdTile.IsChecked.Value)
            {
                TxtTileTitle.IsEnabled = false;
                TxtTileTitle.Text = TxtTitle.Text;
            }
            else
            {
                TxtTileTitle.IsEnabled = true;
            }
        }

        private void TxtTitleTextChanged(object sender, TextChangedEventArgs e)
        {
            TxtTitle.Text = TxtTitle.Text.Trim();
            if (ChkUpdTile.IsChecked != null && ChkUpdTile.IsChecked.Value)
            {
                TxtTileTitle.Text = TxtTitle.Text;
            }
            if (ChkUpdToken.IsChecked != null && ChkUpdToken.IsChecked.Value)
            {
                TxtTokenID.Text = TxtTitle.Text + "Token";
            }
            if (TxtTitle.Text.Length  == 0)
            {
                AddAdorneErr(TxtTitle);
            }
            else
            {
                RemoveAdorneErr(TxtTitle);
                
            }
        }

        private bool ExistAdorneErr(IFrameworkInputElement control)
        {
            return _adorneErroControls.Any(c => c.ControlErr.Name == control.Name);
        }

        private void RemoveAdorneErr(Control control)
        {
            var item = _adorneErroControls.FindLast(c => c.ControlErr.Name == control.Name);
            if (item != null)
            {
                control.BorderBrush = item.DefaultBrush;
                _adorneErroControls.Remove(item);
            }
        }

        private void AddAdorneErr(Control control)
        {
            if (_adorneErroControls.Any(c => c.ControlErr.Name == control.Name))
            {
                if (control.BorderBrush != null && control.BorderBrush != Brushes.Red)
                {
                    control.BorderBrush = Brushes.Red;
                }
            }
            else
            {
                var item = new AdorneLst{DefaultBrush = control.BorderBrush};
                control.BorderBrush = Brushes.Red;
                item.ControlErr = control;
                _adorneErroControls.Add(item);
            }
        }

        private void ChkUpdTokenClick(object sender, RoutedEventArgs e)
        {
            if (ChkUpdToken.IsChecked != null && ChkUpdToken.IsChecked.Value)
            {
                TxtTokenID.IsEnabled = false;
                if (TxtTitle.Text.Trim().Length > 0)
                {
                    TxtTokenID.Text = TxtTitle.Text + "Token";
                }
                else
                {
                    TxtTokenID.Text = string.Empty;
                }
            }
            else
            {
                TxtTokenID.IsEnabled = true;
            }
        }

        private void VersionTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = !Common.AreAllValidNumericChars(e.Text);
            base.OnPreviewTextInput(e);
        }

        private void TxtTileCountTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            e.Handled = !Common.AreAllValidNumericChars(e.Text);
            base.OnPreviewTextInput(e);
        }

        private void BntErroClick(object sender, RoutedEventArgs e)
        {
            if (_errsFromManifest.Length == 0)
            {
                BntErro.Visibility = Visibility.Collapsed;
                return;
            }
            MessageBox.Show(AppRes.LastErr + _errsFromManifest, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void UserControlIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            _isVisible = (bool)e.NewValue;

            if (!(bool)e.OldValue && (bool)e.NewValue && (CboProjects.SelectedIndex == -1))
            {
                Refreshprojects();
            }
        }

        private void ClearAdorneErroUiElement()
        {
            foreach (var item in _adorneErroControls)
            {
                item.ControlErr.BorderBrush = item.DefaultBrush;
            }
            _adorneErroControls.Clear();
        }

        private void AdorneErroUiElement(Control control)
        {
            var item = new AdorneLst{DefaultBrush = control.BorderBrush};
            control.BorderBrush = Brushes.Red;
            item.ControlErr = control;
            _adorneErroControls.Add(item);
        }

        # region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }

        #endregion

        private void TxtTokenIdTextChanged(object sender, TextChangedEventArgs e)
        {
            TxtTokenID.Text = TxtTokenID.Text.Trim();
            if (TxtTokenID.Text.Length == 0)
            {
                AddAdorneErr(TxtTokenID);
            }
            else
            {
                RemoveAdorneErr(TxtTokenID);
            }
        }

        private void TxtAuthorTextChanged(object sender, TextChangedEventArgs e)
        {
            TxtAuthor.Text = TxtAuthor.Text.Trim();
            if (TxtAuthor.Text.Length == 0)
            {
                AddAdorneErr(TxtAuthor);
            }
            else
            {
                RemoveAdorneErr(TxtAuthor);
            }
        }

        private void TxtDescTextChanged(object sender, TextChangedEventArgs e)
        {
            TxtDesc.Text = TxtDesc.Text.Trim();
            if (TxtDesc.Text.Length == 0)
            {
                AddAdorneErr(TxtDesc);
            }
            else
            {
                RemoveAdorneErr(TxtDesc);
            }
        }

        private void TxtPublisherTextChanged(object sender, TextChangedEventArgs e)
        {
            TxtPublisher.Text = TxtPublisher.Text.Trim();
            if (TxtPublisher.Text.Length == 0)
            {
                AddAdorneErr(TxtPublisher);
            }
            else
            {
                RemoveAdorneErr(TxtPublisher);
            }
        }

        private void VerMaiorTextChanged(object sender, TextChangedEventArgs e)
        {
            VerMaior.Text = VerMaior.Text.Trim();
            if (VerMaior.Text.Length == 0)
            {
                AddAdorneErr(VerMaior);
            }
            else
            {
                RemoveAdorneErr(VerMaior);
            }
        }

        private void VerMenorTextChanged(object sender, TextChangedEventArgs e)
        {
            VerMenor.Text = VerMenor.Text.Trim();
            if (VerMenor.Text.Length == 0)
            {
                AddAdorneErr(VerMenor);
            }
            else
            {
                RemoveAdorneErr(VerMenor);
            }
        }

        private void CboIconApppSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CboIconAppp.SelectedIndex < 0)
            {
                AddAdorneErr(CboIconAppp);
            }
            else
            {
                RemoveAdorneErr(CboIconAppp);
            }
        }

        private void CboNavPageSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CboNavPage.SelectedIndex < 0)
            {
                AddAdorneErr(CboNavPage);
            }
            else
            {
                RemoveAdorneErr(CboNavPage);
            }
        }

        private void TxtTileCountTextChanged(object sender, TextChangedEventArgs e)
        {
            TxtTileCount.Text = TxtTileCount.Text.Trim();
            if (TxtTileCount.Text.Length == 0)
            {
                AddAdorneErr(TxtTileCount);
            }
            else
            {
                RemoveAdorneErr(TxtTileCount);
                if (CboIconBg.SelectedIndex >= 0)
                {
                    RemoveAdorneErr(ExpTile);
                }
            }
        }

        private void TxtTileTitleTextChanged(object sender, TextChangedEventArgs e)
        {
            TxtTileTitle.Text = TxtTileTitle.Text.Trim();
        }

        private void CboIconBgSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CboIconBg.SelectedIndex < 0)
            {
                AddAdorneErr(CboIconBg);
            }
            else
            {
                RemoveAdorneErr(CboIconBg);
                if (TxtTileCount.Text.Length > 0)
                {
                    RemoveAdorneErr(ExpTile);
                }
            }
        }

        private void Opt32PixelChecked(object sender, RoutedEventArgs e)
        {
            RemoveAdorneErr(opt32pixel);
            RemoveAdorneErr(opt16pixel);
            ValidateExpMore();
        }

        private void Opt16PixelChecked(object sender, RoutedEventArgs e)
        {
            RemoveAdorneErr(opt32pixel);
            RemoveAdorneErr(opt16pixel);
            ValidateExpMore();
        }

        private void ValidateExpMore()
        {
            if (ExistAdorneErr(ChkHasSettings) ||
                ExistAdorneErr(ChkIsBeta) ||
                ExistAdorneErr(ChkSingleInst) ||
                ExistAdorneErr(ChkHubType1) ||
                ExistAdorneErr(opt32pixel) ||
                ExistAdorneErr(opt16pixel))
            {
                return;
            }
            RemoveAdorneErr(ExpMore);
        }

        private void ChkInExpMore(object sender, RoutedEventArgs e)
        {
            RemoveAdorneErr((CheckBox)sender);
            ValidateExpMore();
        }

        private void ExpCapExpanded(object sender, RoutedEventArgs e)
        {
            RemoveAdorneErr(ExpCap);
        }

        private void VerRevTextChanged(object sender, TextChangedEventArgs e)
        {
            VerRev.Text = VerRev.Text.Trim();
            if (VerRev.Text.Length == 0)
            {
                VerBuild.Text = string.Empty;
            }
        }

        private void VerBuildTextChanged(object sender, TextChangedEventArgs e)
        {
            VerBuild.Text = VerBuild.Text.Trim();
            if (VerBuild.Text.Length > 0 && VerRev.Text.Trim().Length == 0)
            {
                VerRev.Text = "0";
            }
        }

        private void RefreshIconsMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (!CboIconAppp.IsEnabled || !CboIconBg.IsEnabled) return;
            WaitReading.Visibility = Visibility.Visible;
            CboIconAppp.IsEnabled = false;
            CboIconBg.IsEnabled = false;
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(BackgroundChangeIcons));
        }

        private void BackgroundChangeIcons()
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            try
            {
                #pragma warning disable 168
                var dummy = _seletedProject.Name;
                #pragma warning restore 168
            }
            catch (Exception ex)
            {
                WaitReading.Visibility = Visibility.Collapsed;
                CboIconAppp.IsEnabled = true;
                CboIconBg.IsEnabled = true;
                Cursor = oldcur;
                MessageBox.Show(ex.Message, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            var itemsel1 = CboIconAppp.Text;
            var itemsel2 = CboIconBg.Text;
            _imagesSeletedProject = Common.GetListFilesFromProject(_seletedProject,
                                                                   new[] { ".PNG", ".JPG", ".JPEG", ".BMP" });

            CboIconAppp.ItemsSource = _imagesSeletedProject;
            CboIconAppp.Text = itemsel1;
            CboIconBg.ItemsSource = _imagesSeletedProject;
            CboIconBg.Text = itemsel2;
            WaitReading.Visibility = Visibility.Collapsed;
            CboIconAppp.IsEnabled = true;
            CboIconBg.IsEnabled = true;
            Cursor = oldcur;
        }

        private void RefreshNavPgMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (!CboNavPage.IsEnabled) return;
            WaitReading.Visibility = Visibility.Visible;
            CboNavPage.IsEnabled = false;
            Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(BackgroundChangePageNav));
        }

        private void BackgroundChangePageNav()
        {
            var oldcur = Cursor;
            Cursor = System.Windows.Input.Cursors.Wait;
            try
            {
                #pragma warning disable 168
                var dummy = _seletedProject.Name;
                #pragma warning restore 168
            }
            catch (Exception ex)
            {
                WaitReading.Visibility = Visibility.Collapsed;
                CboIconAppp.IsEnabled = true;
                CboIconBg.IsEnabled = true;
                Cursor = oldcur;
                MessageBox.Show(ex.Message, AppRes.TitleWindows, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            var itemsel = CboNavPage.Text;
            _fileXamlseletedProject = Common.GetListFilesFromProject(_seletedProject,
                                                                   new[] { ".XAML" });

            CboNavPage.ItemsSource = _fileXamlseletedProject;
            CboNavPage.Text = itemsel;
            WaitReading.Visibility = Visibility.Collapsed;
            CboNavPage.IsEnabled = true;
            Cursor = oldcur;
        }

        private void RefreshMouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            ((TextBlock)sender).FontWeight = FontWeights.Bold;
        }

        private void RefreshMouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            ((TextBlock)sender).FontWeight = FontWeights.Normal;
        }
    }
}
